package gsw.tool.eventbus.response;

import com.google.gson.Gson;

import gsw.tool.eventbus.core.ObjectCenter;
import gsw.tool.eventbus.core.TypeCenter;
import gsw.tool.eventbus.request.Request;
import gsw.tool.eventbus.request.RequestBean;
import gsw.tool.eventbus.request.RequestParameter;

/**
 * Responce生成器
 */
public abstract class ResponceMake {
    //响应结果的类
    protected Class<?> reslutClass;
    //响应结果的参数
    protected Object[] mParameters;
    //响应结果的参数类型
    protected Class<?>[] parameterTypes = null;
    protected Gson GSON = new Gson();
    protected TypeCenter typeCenter = TypeCenter.getInstance();
    protected static final ObjectCenter OBJECT_CENTER = ObjectCenter.getInstance();

    protected abstract Object invokeMethod();

    protected abstract void setMethod(RequestBean requestBean);

    /**
     * 生成Responce
     *
     * @param request 请求
     */
    public Response makeResponce(Request request) {
        //请求数据
        RequestBean requestBean = GSON.fromJson(request.getData(), RequestBean.class);
        reslutClass = typeCenter.getClassType(requestBean.getResultClassName());
        RequestParameter[] requestParameters = requestBean.getRequestParameter();
        //得到实际的参数
        if (requestParameters != null && requestParameters.length > 0) {
            mParameters = new Object[requestParameters.length];
            parameterTypes = new Class<?>[requestParameters.length];
            for (int i = 0; i < requestParameters.length; i++) {
                RequestParameter requestParameter = requestParameters[i];
                Class<?> clazz = typeCenter.getClassType(requestParameter.getParameterClassName());
                parameterTypes[i] = clazz;
                mParameters[i] = GSON.fromJson(requestParameter.getParameterValue(), clazz);
            }
        } else {
            mParameters = new Object[0];
        }

        setMethod(requestBean);
        Object resultObject = invokeMethod();
        //响应数据
        ResponceBean responceBean = new ResponceBean(resultObject);
        //把的到的结果序列化成字符串
        String data = GSON.toJson(responceBean);
        Response response = new Response(data);
        return response;
    }
}
